<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="题型名称" prop="typeName">
        <el-input
          v-model="queryParams.typeName"
          placeholder="请输入题型名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="题面" prop="content">
        <el-input
          v-model="queryParams.content"
          placeholder="请输入题面"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:store:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:store:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:store:remove']"
        >删除</el-button>
      </el-col>
     <!--  <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:store:export']"
        >导出</el-button>
      </el-col> -->
	  <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="questionStoreList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="标识" align="center" width="55" prop="id" />
      <el-table-column label="版本号" align="center" width="155" prop="vesionCode" />
      <el-table-column label="题型" align="center" width="155" prop="typeCode" :formatter="typeCodeFormat" />
      <el-table-column label="题面" align="center" width="400" prop="content" >
        <template slot-scope="scope">
                  <span v-html="scope.row.content"></span>
                </template>
      </el-table-column>
       <el-table-column label="标准答案" align="center" width="155" prop="standartAnswer" />
<!--       <el-table-column label="参考答案" align="center" width="155" prop="suggestAnswer" />
 -->      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:store:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:store:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改[题库]对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="版本号" prop="vesionCode">
          <el-input readonly v-model="form.vesionCode" placeholder="请输入版本号" />
        </el-form-item>
      <!-- <el-form-item label="章节名称" prop="courseCatalogId">
            <el-select v-model="form.courseCatalogId"  placeholder="请选择章节名称">
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="题型">
          <el-radio-group  @change="agreeChange" v-model="form.typeCode">
            <el-radio
              v-for="dict in typeCodeOptions"
              :key="dict.dictValue"
              :label="parseInt(dict.dictValue)"
              
            >{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="题面" prop="content">
          <Editor v-model="form.content" />
        </el-form-item>
          <br>
        <el-form-item label="选项" prop="options">
          <br>
          <el-form>
             <el-form-item
              v-for="(domain, index) in domains"
              :label="'选项'+cities[index]"
              :key="domain.key"
              :prop="'domains.' + index + '.value'"
            >
              <Editor v-model="domain.value" />
              <br>
              <br>
              <el-button @click.prevent="removeDomain(domain)">删除</el-button>
            </el-form-item>
            <el-form-item>
              <el-button v-show="form.typeCode != 1"  type="primary" @click="addDomain">新增选项</el-button>
            </el-form-item>
          </el-form>
        </el-form-item>
        <el-form-item label="标准答案" prop="standartAnswer">
          <!-- <el-input v-model="form.standartAnswer" placeholder="请输入标准答案，如单选：A 多选：A,B" /> -->
          <template>
              <el-checkbox-group v-model="checkedCities" >
                <el-checkbox-button :checked="isChecked"  @change="checkedFun(index,city)" v-for="(city,index) in cities" :label="city" :key="index">{{city}}</el-checkbox-button>
              </el-checkbox-group>
            </template>
            
        </el-form-item>
        <!-- <el-form-item label="参考答案" prop="suggestAnswer">
          <el-input v-model="form.suggestAnswer" placeholder="请输入参考答案" />
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listquestionStore, getquestionStore, delquestionStore, addquestionStore, updatequestionStore, exportquestionStore,getCourseCat } from "@/api/system/questionStore";
import Editor from '@/components/Editor';

export default {
  name: "questionStore",
     components: {
    Editor
  },
  data() {
    return {
      dxList:[],
      dx:'',
      tmlx: undefined,
      xx:[],
      da:'',
      optionsIndex:'',
      //答案是否被选中
      isChecked:false,
      //被选中
      checkedCities: [],
      //全部选项
      cities: [],
      options:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // [题库]表格数据
      questionStoreList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 题型字典
      typeCodeOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        typeName: null,
        content: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        vesionCode: [
          { required: true, message: "版本号不能为空", trigger: "blur" }
        ],
        typeCode: [
          { required: true, message: "题型不能为空", trigger: "blur" }
        ],
        content: [
          { required: true, message: "题面不能为空", trigger: "blur" }
        ],
        standartAnswer: [
          { required: true, message: "标准答案不能为空", trigger: "blur" }
        ],
        options: [
          { required: true, message: "选项不能为空", trigger: "blur" }
        ],
        suggestAnswer: [
          { required: true, message: "参考答案不能为空", trigger: "blur" }
        ],
      },
      domains: [
      ]
    };
  },
  created() {
    this.getCourseCat();
    this.getList();
    this.getDicts("question_store_code").then(response => {
      this.typeCodeOptions = response.data;
    });
  },
  methods: {
    checkedFun(index,city){
      let typeCode = this.form.typeCode;
      if(typeCode == 1 || typeCode == 2){
        if (this.checkedCities.length > 1) {
            this.checkedCities.shift();
        }
      }
    },
      removeDomain(item) {
        var index = this.domains.indexOf(item)
        if (index !== -1) {
          this.domains.splice(index, 1);
          this.cities.splice(index,1);
        }
        this.cities = [];
        let leng = this.domains.length;
        if(leng == 1){
          this.cities = ['A'];
        }else if(leng == 2){
          this.cities = ['A','B'];
        }else if(leng == 3){
          this.cities = ['A','B','C'];
        }else if(leng == 4){
          this.cities = ['A','B','C','D'];
        }else if(leng == 5){
          this.cities = ['A','B','C','D','E'];
        }
      },
      agreeChange(){
        this.cities = [];
        this.domains = [];
        this.form.standartAnswer = '';
       if(this.form.typeCode == 1){
        this.cities.push('对');
        this.cities.push('错');
      }
         if (this.form.id != null) {
          this.checkedCities = this.form.standartAnswer.split(",");
          var st  = this.form.options.split('@#$');
          let stLength = st.length;
          if(this.form.typeCode == this.tmlx){
            this.domains = this.dxList;
             this.cities = this.xx;
             this.checkedCities = this.dx.split("@#$");
          }
         
         }
      },
      addDomain() {
        let self = this;
        this.form.options = '123';
        let typeCode = this.form.typeCode;
        if(this.domains.length==0 && typeCode != 1){
            self.cities.push('A');
            this.domains.push({
          value: '',
          key: Date.now()
        });
        }else if(this.domains.length==1 && typeCode != 1){
            self.cities.push('B');
            this.domains.push({
          value: '',
          key: Date.now()
        });
        }else if(this.domains.length==2  && (typeCode ==  2 || typeCode ==  3)){
            self.cities.push('C');
            this.domains.push({
          value: '',
          key: Date.now()
        });
        }else if(this.domains.length==3  && (typeCode ==  2 || typeCode ==  3)){
            self.cities.push('D');
            this.domains.push({
          value: '',
          key: Date.now()
        });
        }else if(this.domains.length==4  && (typeCode ==  2 || typeCode ==  3)){
            self.cities.push('E');
            this.domains.push({
          value: '',
          key: Date.now()
        });
        }
      },
    /** 查询[题库]列表  getCourseCat */
    getCourseCat() {
      this.loading = true;
      getCourseCat().then(response => {
        this.options = response.data;
      });
    },
    getList() {
      this.loading = true;
      listquestionStore(this.queryParams).then(response => {
        this.questionStoreList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 题型字典翻译
    typeCodeFormat(row, column) {
      return this.selectDictLabel(this.typeCodeOptions, row.typeCode);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
      this.cities=[];
      this.checkedCities=[];
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        vesionCode: null,
        typeCode: 1,
        typeName: null,
        content: null,
        options: null,
        standartAnswer: null,
        suggestAnswer: null,
        createDt: null,
        modifyDt: null
      };
      this.resetForm("form");
      this.cities = [];
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.domains = [];
      this.open = true;
      this.title = "添加习题";
      var time = Date.parse( new Date() ).toString();//获取到毫秒的时间戳，精确到毫秒
      time = time.substr(0,10);//精确到秒
      this.form.vesionCode = time;
      if(this.form.typeCode == 1){
        this.cities.push('对');
        this.cities.push('错');
      }
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.domains = [];
      this.checkedCities = [];
      const id = row.id || this.ids
      getquestionStore(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改习题";
        if(!this.form.options){
          this.domains=[];
        }else{
          this.checkedCities = this.form.standartAnswer.split(",");
          var st  = this.form.options.split('@#$');
          let stLength = st.length;
          if(this.form.typeCode != 1)
          for(var i= 0;i<stLength;i++){
            this.domains.push({
              value:st[i]
            });
          }
            
          switch(stLength) {
              case 2:
                if(this.form.typeCode == 1)
                this.cities = ['对','错'];
                else{
                  this.cities = ['A','B'];
                }
                break;
              case 3:
                this.cities = ['A','B','C'];
                 break;
              case 4:
                this.cities = ['A','B','C','D'];
                 break;
              case 5:
                this.cities = ['A','B','C','D','E'];
                 break;
          } 
          this.dxList = this.domains;
            this.dx = this.form.standartAnswer;
            this.tmlx = this.form.typeCode;
            this.xx = this.cities;
        }
        

      });
    },
    /** 提交按钮 */
    submitForm() {
      console.log(this.checkedCities.length);
      var self = this;
      //获取当前的题型
      let type = this.form.typeCode;
      if(type==1 || type==2){
        if(this.checkedCities.length==1){
          self.form.standartAnswer=this.checkedCities[0]
        }else{
          this.msgSuccess("请选择一个正确答案");
        }
      }else if(type==3){

        if(this.checkedCities.length<2){
          this.msgSuccess("请至少选择一个正确答案");
        }else{
          let zqda = "";
          for(var i=0;i<self.checkedCities.length;i++){

              zqda+=self.checkedCities[i]+","
          }
          self.form.standartAnswer = zqda.substring(0,zqda.length-1)
        }
      }
      
      this.$refs["form"].validate(valid => {
        if(this.form.typeCode == 1){
          this.form.options = "对@#$错@#$";
        }else{
        var str = '';
        for(var i=0;i<this.domains.length;i++){
          if(this.form.id == null)
           str += this.cities[i]+"."+this.domains[i]['value']+'@#$' 
          else
          str += this.domains[i]['value']+'@#$' 
        }
        this.form.options = str;
        }
        if (valid) {
          if (this.form.id != null) {
            updatequestionStore(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            addquestionStore(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除习题管理编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delquestionStore(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有[题库]数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportquestionStore(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
    }
  }
};
</script>
<style scoped>
@import url("//unpkg.com/element-ui@2.13.2/lib/theme-chalk/index.css");
</style>
